package com.kin.tools.impl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.kin.controller.UserController;
import com.kin.service.IGroupService;
import com.kin.service.IPageService;
import com.kin.service.IRoleService;
import com.kin.service.IUserPermissionService;
import com.kin.tools.IToolsService;

/**
 * SpringMvc拦截器
 * @author lauvinson
 * @time 2017年7月14日09:20:42
 */
@SessionAttributes({"User","userid","grouid"})
public class Interceptor implements HandlerInterceptor{
	
	private static Logger logger = Logger.getLogger(Interceptor.class);
	private static String USER_ID = "userid";
	private static String GROUP_ID = "groupid";
	private static String USER = "User";
	private static String USER_NAME ="username";
	private static String SIGN_IN = "SignIn";

	@Resource
	private UserController userController;
	
	@Resource
	private IToolsService toolsService;
	
	@Resource
	private IUserPermissionService userPermissionService;
	
	@Resource
	private IGroupService groupService;
	
	@Resource
	private IPageService pageService;
	
	@Resource
	private IRoleService roleService;
	

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("SecurityInterceptor preHandle:"+request.getContextPath()+","+request.getRequestURI()+","+request.getMethod());
        return getPermission(request, response, handler);
        
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }
    
    
    
    
    
    //权限拦截处理
    public boolean getPermission(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
    	
        try{
	        if(request.getSession().getAttribute(USER_ID)!= null)
	       {
	        	logger.info("userName:"+toolsService.stringToJsonObject((request.getSession().getAttribute(USER).toString().trim())).getString(USER_NAME).trim()
	        			
	        			);
	        	logger.info("groupName:"+
	        			groupService.getGroupById(Integer.parseInt(request.getSession().getAttribute(GROUP_ID).toString().trim())).getGroupname().trim()
	        			);
	        	logger.info("requestUrl"+request.getRequestURI().replaceAll(request.getContextPath(),""));
	        	int state = roleService.getPermission(Integer.parseInt(request.getSession().getAttribute(USER_ID).toString().trim()), request.getRequestURI().replace(request.getContextPath().trim(), ""));
		        if(state == 1)
		        {
		        	return true;
		        }
		        else if(state == 0)
		        {
		        	if(userPermissionService.getUserPermissionByUserIdAndPageId(Integer.parseInt(request.getSession().getAttribute(USER_ID).toString().trim()),pageService.getPageByUrl(request.getRequestURI().replace(request.getContextPath().trim(), "")).getPageid()) != null
		        			&& userPermissionService.getUserPermissionByUserIdAndPageId(Integer.parseInt(request.getSession().getAttribute(USER_ID).toString().trim()),pageService.getPageByUrl(request.getRequestURI().replace(request.getContextPath().trim(), "")).getPageid()).getState()==1)
		        		return true;
		        	else
		        	{
		        		response.sendError(403);
			        	return false;
		        	}
		        }
		        else if(state ==2)
		        {
		        	response.sendError(404);
		        	logger.info("notFoun request:"+request.getRequestURI().replace(request.getContextPath(), ""));
		        	return false;
		        }
		        else{
		        	return false;
		        }
	       }
	       else
	       {
	    	   response.sendError(401);
	    	   return false;
	       }
       }
       catch(NullPointerException e)
       {
    	   e.printStackTrace();
    	   response.sendError(500);
    	   logger.error("Interceptor Exception");
    	   return false;
       }
    }
}